<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字" size="small"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getTableData" icon="el-icon-search" size="small">执行查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary"  icon="el-icon-plus" size="small"  v-on:click="addTeacher" >讲师新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column  label="头像">
				<template scope="scope">
					<el-image style="width: 40px;height: 40px"
							:src="scope.row.headImg"></el-image>
				</template>
			</el-table-column>
			<el-table-column prop="name" label="名称" >
			</el-table-column>
			<el-table-column prop="position" label="职位"  >
			</el-table-column>
			<el-table-column prop="tags" label="标签"  >
			</el-table-column>
      <el-table-column prop="technology" label="技术栈" width="200" >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top" >
            <div style="width: 400px;">{{ scope.row.technology }}</div>
            <div slot="reference" class="name-wrapper" >
              <el-tag >
                {{ scope.row.technology}}
              </el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
			<el-table-column prop="intro" label="介绍" width="200" >
				<template slot-scope="scope">
					<el-popover trigger="hover" placement="top" >
						<div style="width: 400px;">{{ scope.row.intro }}</div>
						<div slot="reference" class="name-wrapper" >
							<el-tag >
								{{ scope.row.intro }}
							</el-tag>
						</div>
					</el-popover>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200">
				<template scope="scope">
					<el-button size="small"  @click="edit(scope.row)" icon="el-icon-edit" type="primary">编辑</el-button>
					<el-button type="danger" size="small" @click="del(scope.row)" icon="el-icon-remove">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" icon="el-icon-remove" size="small">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="saveForm.position" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="saveForm.tags" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="headImg" style="width: 400px" >
          <!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://imachen-bucket.oss-cn-chengdu.aliyuncs.com"
              :data="uploadImgData"
              :file-list="fileList"
              list-type="picture"
              :before-upload="beforeImgUpload"
              :on-success="handleImgSuccess"
              :limit="1">
            <el-button size="small" type="primary"  icon="el-icon-picture-outline">上传头像</el-button>
            &nbsp;&nbsp;<span slot="tip" class="el-upload__tip">支持500kb，格式jpg</span>
          </el-upload>
        </el-form-item>
        <el-form-item label="技术栈" prop="technology">
          <el-input v-model="saveForm.technology" auto-complete="off" type="textarea" ></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off" type="textarea" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>

	export default {
		data() {
			return {
        uploadImgData:{},
        fileList:[],

				filters: {
					keyword: ''
				},
				tableData: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels:[],


        // 添加或修改
        saveFormVisible: false,//编辑界面是否显示
        title: "",
        saveLoading: false,
        saveFormRules: {
          intro: [
            { required: true, message: '请输入讲师介绍', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入讲师名称', trigger: 'blur' }
          ],
          technology: [
            { required: true, message: '请输入讲师技术栈', trigger: 'blur' }
          ],
          position: [
            { required: true, message: '请输入讲师职位', trigger: 'blur' }
          ],
          tags: [
            { required: true, message: '请输入讲师标签', trigger: 'blur' }
          ],
        },
        //编辑界面数据
        saveForm: {
          id: null,
          name: '',
          intro: '',  // 介绍
          technology: '', // 技术栈
          position: '',  // 职位
          headImg: '', // 头像
          tags: ''  // 标签
        },
			}

		},
		methods: {
			selsChange(sels){
				this.sels = sels;
			},
			//性别显示转换
			formatState: function (row, column) {
				return row.sex == 1 ? '禁用' : '启用';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getTableData();
			},
			//获取用户列表
			getTableData() {
				let para = {
					page: this.page,
					keyword: this.filters.keyword
				};
				this.listLoading = true; //显示加载圈
				this.$http.post("/course/teacher/pagelist",para).then(result=>{
          let {success , data, message ,code} = result.data;
          if(success){
            this.total = data.total;
            this.tableData = data.rows;
          }else{
            this.$message({ message: "数据加载失败["+message+"]!!!", type: 'error' });
          }
          this.listLoading = false;
        }).catch(error => {
          this.listLoading = false;
          this.$message({ message: "数据加载失败["+error.message+"]", type: 'error' });
        })
			},
			del: function (row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/course/teacher/" + row.id).then(res => {
            // 成功之后的处理
            if (res.data.success) {
              this.getTableData();
            } else {
              this.$message.error("系统繁忙，请稍后重试！！")
            }
            this.listLoading = false;
          }).catch(() => {
            this.$message.error("系统繁忙，请稍后重试！！")
            this.listLoading = false;
          })
        }).catch(()=>{

        });
      },


      batchRemove: function () {
        var ids = this.sels.map(item => item.id);//数组 [1,3,5]
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => { //点击确定走这里
          this.listLoading = true;
          this.$http.patch("/course/teacher/patchDelete/",ids).then(res=>{
            if(res.data.success){
           //   this.currentPage = 1;
              this.getTableData();
            }else{
              this.$message.error("系统繁忙(500),请稍后重试！")
            }
            this.listLoading = false;
          }).catch(res=>{
            this.$message.error("系统繁忙(404/400),请稍后重试！")
            this.listLoading = false;
          })
        }).catch(() => {
        });
      },

      edit: function (row) {
        this.title = "编辑讲师信息";
        this.saveForm = Object.assign({}, row);

        //图片回显
        this.fileList=[];
          let url=row.headImg
        this.fileList.push({
          'url':url
        })
        this.saveFormVisible = true;
      },
      addTeacher: function () {
			  this.fileList = [];
        this.title = "添加讲师信息";
        this.saveForm = {
          id: null,
          name: '',
          intro: '',
          technology: '',
          position: '',
          headImg: '',
          tags: ''
        };
        this.saveFormVisible = true;
      },
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              this.$http.post("/course/teacher/save",this.saveForm).then(res=>{
                if(res.data.success){
                  this.getTableData();
                }else {
                  this.$message.error("系统繁忙(500),请稍后重试！")
                }
                this.saveLoading = false;
              }).catch(res=>{
                this.$message.error("系统繁忙(404/400),请稍后重试！")
                this.saveLoading = false;
              })
              // 关闭对话框
              this.saveFormVisible = false;
            });
          }
        });
      },
      async getSign(data){
        //让这个请求变成同步请求
        await this.$http.get("/common/oss/sign").then(response=>{
          //设置相关的参数
          var resultObj = response.data.data;
          data.policy = resultObj.policy;
          data.signature = resultObj.signature;
          data.ossaccessKeyId = resultObj.accessid;
          data.dir = resultObj.dir;
          data.host = resultObj.host;
          //上传的文件名，使用UUID处理一下
          data.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
        });
      },
      //文件上传===============================================================
      getUUID() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        var uuid = s.join("");
        return uuid;
      },
      async beforeImgUpload(){
        await this.getSign(this.uploadImgData);
      },
      handleImgSuccess(res, file) {
        var urlPath = this.uploadImgData.host + '/' + this.uploadImgData.key.replace("${filename}",file.name) ;
        this.saveForm.headImg = urlPath;
        this.$message({message: '上传成功', type: 'success' });
      },

		},
		mounted() {
			this.getTableData();
		}
	}

</script>

<style scoped>

</style>